package com.jams.goodox.activity.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hangzhou.jin.customview.LoadView;
import com.hangzhou.jin.customview.SpaceItemDecoration;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.adapter.PictureGroupAdapter;
import com.jams.goodox.constant.Constant;
import com.jams.goodox.entity.AnnexBean;
import com.jams.goodox.entity.FastCarOrder;
import com.jams.goodox.entity.PageInfo;
import com.jams.goodox.entity.resp.FastCarListResp;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.FastCarService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.TimeUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.UserUtils;
import com.jams.goodox.utils.Utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import uama.hangzhou.image.browse.ImagePagerActivity;
import uama.hangzhou.image.widget.MyGridView;

import static android.app.Activity.RESULT_OK;

/**
 * 社交主页
 */
public class SocialIntercourseFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    @Bind(R.id.tv_chat_start_time)
    TextView tvChatStartTime;
    @Bind(R.id.iv_chat)
    ImageView ivChat;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.srf_social)
    SwipeRefreshLayout srfSocial;
    @Bind(R.id.rl_driver)
    RelativeLayout rl_driver;
    @Bind(R.id.loadView)
    LoadView loadView;

    View rootView;

    private int curPage = 1;

    private BaseQuickAdapter mAdapter;
    private List<FastCarOrder> fastCarBeanList;

    private boolean isIssueRoute;//是否认证过车辆信息

    private MaterialDialog.Builder checkInDialog;//审核对话框

    public static SocialIntercourseFragment newInstance(String param1) {
        SocialIntercourseFragment fragment = new SocialIntercourseFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.social_intercourse, container, false);
        }
        ButterKnife.bind(this, rootView);
        init();
        return rootView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void init() {
        checkInDialog = new MaterialDialog.Builder(getActivity()).content("您还未登记车辆信息，是否立刻认证为车主？").positiveText("取消").negativeText("去认证").onNegative(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            }
        });
        initRecycleView();
        srfSocial.setOnRefreshListener(this);
        onRefresh();
    }

    @OnClick({R.id.rl_fun, R.id.rl_driver, R.id.rl_chat})
    public void onViewClicked(View view) {
        if (Utils.isFastDoubleClick()) return;
        switch (view.getId()) {
            case R.id.rl_fun://轻松一刻
                ToastUtil.show(getString(R.string.function_is_building));
//                qStartActivity(FunnyTimeListActivity.class);
                break;
            case R.id.rl_driver: //好司机带带我
                rl_driver.setEnabled(false);
                checkUserIsInBlackList();
                break;
            case R.id.rl_chat://定点开聊
                ToastUtil.show(getString(R.string.function_is_building));
//                qStartActivity(ChatTimeActivity.class);
                break;
        }
    }

    /**
     * 好司机带带我检查是否加入黑名单
     */
    private void checkUserIsInBlackList() {
        enqueue(createCallService(FastCarService.class).checkUserIsInBlackList(DataCacheManager.getInstance().getUser().getUserId()), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                rl_driver.setEnabled(true);
//                qStartActivity(FastCarListActivity.class);
            }

            @Override
            public void onError(String msg) {
                rl_driver.setEnabled(true);
                ToastUtil.show(msg);
            }
        });
    }

    /**
     * 初始化列表
     */
    private void initRecycleView() {
        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleView.addItemDecoration(new SpaceItemDecoration(DensityUtil.dp2px(getActivity(), 8f)));

        fastCarBeanList = new ArrayList<>();
        mAdapter = new BaseQuickAdapter<FastCarOrder>(R.layout.home_fastcar_item, fastCarBeanList) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, final FastCarOrder item) {
                baseViewHolder.setText(R.id.tv_car_time, item.getDateTime());
                baseViewHolder.setText(R.id.tv_people_num, item.getPeopleNumber());
                baseViewHolder.setText(R.id.tv_start_place, item.getStartPlace());
                baseViewHolder.setText(R.id.tv_end_place, item.getEndPlace());
                TextView tx_car_pay = baseViewHolder.getView(R.id.tv_car_pay);
                tx_car_pay.setCompoundDrawablesWithIntrinsicBounds(item.isPayMoney() ? R.mipmap.car_red : R.mipmap.car_gift, 0, 0, 0);
                tx_car_pay.setText(item.isPayMoney() ? item.getPayMoney() + "元" : item.getGoodName());
                MyGridView blankClickGridView = baseViewHolder.getView(R.id.gv_home_driver_item);
                blankClickGridView.setFocusable(false);
                blankClickGridView.setVisibility(item.getAnnexBeanList().size() == 0 ? View.GONE : View.VISIBLE);
                setImageList(blankClickGridView, item.getAnnexBeanList());
                baseViewHolder.setOnClickListener(R.id.tv_rob, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (!isIssueRoute) {
                            checkInDialog.show();
                            return;
                        }
                        if (!UserUtils.isVerifier()) {//提交过车主信息未通过
                            ToastUtil.show(getActivity(), "车主身份认证中");
                            return;
                        }
                        //已认证车主通过
                        robOrder(item.getOrderId());
                    }
                });
            }
        };
        mAdapter.openLoadMore(20, true);

        // 自定义上拉View
        mAdapter.setLoadingView(getLoadMoreBootView(getContext()));
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                getData(true);
            }
        });

        recycleView.setAdapter(mAdapter);
    }

    //设置图片
    private void setImageList(MyGridView gridView, final List<AnnexBean> imageList) {
        PictureGroupAdapter gridAdapter = new PictureGroupAdapter(getActivity(), imageList, 54, 9);
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (imageList.size() == 4 && position == 2) return;
                List<String> imageListNew = new ArrayList<>();
                for (int i = 0; i < imageList.size(); i++) {
                    imageListNew.add(imageList.get(i).getUrlPath());
                }
                if (imageListNew.size() == 4 && position > 1) {
                    position--;
                }
                Intent intent = new Intent(getActivity(), ImagePagerActivity.class);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (Serializable) imageListNew);
                startActivity(intent);
            }
        });
    }

    /**
     * 抢单
     */
    private void robOrder(String orderId) {
        showLoading();
        enqueue(createCallService(FastCarService.class).robOrder(orderId, SePref.getUserId()), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                ToastUtil.show("抢单成功");
                misLoading();
                onRefresh();
            }

            @Override
            public void onError(String msg) {
                misLoading();
                ToastUtil.show(msg);
            }
        });
    }

    /**
     * 获取数据
     *
     * @param isLoadMore 是否加载更多
     */
    private void getData(boolean isLoadMore) {
        Map<String, String> params = Constant.getPagerParams(isLoadMore ? curPage + 1 : curPage);
        params.put("userId", SePref.getUserId());
        enqueue(createCallService(FastCarService.class).getRideHomeInfo(params), new RetrofitCallbackListener<FastCarListResp>() {
            @Override
            public void onSuccess(Call<FastCarListResp> call, FastCarListResp result) {
                loadView.loadComplete();
                srfSocial.setRefreshing(false);
                if (result.getData() == null) return;
                isIssueRoute = result.getData().isFlag();
                if (result.getData().getPageInfo() == null || result.getData().getResultList() == null) {
                    if (fastCarBeanList.size() == 0)
                        loadView.loadCompleteNoData(R.mipmap.holder_no_common, "暂无内容");
                    mAdapter.notifyDataChangedAfterLoadMore(false);
                    return;
                }
                PageInfo pageInfo = result.getData().getPageInfo();
                curPage = pageInfo.getCurPage();
                if (curPage == 1) fastCarBeanList.clear();
                fastCarBeanList.addAll(result.getData().transform());
                mAdapter.notifyDataChangedAfterLoadMore(pageInfo.isHasMore());
                if (fastCarBeanList.size() == 0)
                    loadView.loadCompleteNoData(R.mipmap.holder_no_common, "暂无内容");
            }

            @Override
            public void onError(String msg) {
                loadView.loadComplete();
                srfSocial.setRefreshing(false);
                mAdapter.notifyDataChangedAfterLoadMore(false);
                if (fastCarBeanList.size() == 0)
                    loadView.loadCompleteNoData(R.mipmap.holder_no_common, "暂无内容");
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1991) {
            if (resultCode == RESULT_OK) {
                onRefresh();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (TimeUtils.getTimeDifference(TimeUtils.MINUTE, SePref.getSocialRefreshTime(), TimeUtils.getSystemTime()) > 15) {
            onRefresh();
        }
    }

    @Override
    public void onRefresh() {
        SePref.putSocialRefreshTime();
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                try {
                    srfSocial.setRefreshing(true);
                    curPage = 1;
                    getData(false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }
}
